//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics.Contracts;
using System.IO;
using OpenLS.Spreadsheet.Formats.Biff.Tokens;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal sealed class ArrayRecord : WorksheetLevelRecord
    {
        private RangeAddress8 _address;
        private ushort grbit;
        private CellParsedFormula _formula;

        public RangeAddress Address
        {
            get { return (RangeAddress)_address; }
        }

        public FormulaRecord FormulaRecord { get; private set; }

        public CellParsedFormula Formula
        {
            get { return _formula; }
        }


        internal override void Apply(BiffReaderWorksheetContext context)
        {
            var f = context.PreviousRecord as FormulaRecord;
            FormulaRecord = f;
            if (f != null)
            {
                f.ArrayInfo = this;
            }
            else
            {
                Contract.Assert(false, "wrong record");
            }
        }

        internal override BiffRecordType RecordType
        {
            get{ return BiffRecordType.Array;}
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            _address.Write(context.Writer);
            context.Write(this.grbit);
            var chn = _formula.TotalTokenByteLength(FormulaReadContextType.Default);
            context.Write(chn);
            _formula.Write(context.Writer);
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            _address.Read(context.Reader) ; 
            grbit = context.ReadUInt16();
            var chn = context.ReadInt32();
           // var cce = reader.ReadUInt16();
            _formula = new CellParsedFormula();
            Formula.Read(new FormulaReadContext(context.Reader, FormulaReadContextType.Default));
        }
    }
}